"use client";
import { useEffect, useRef, forwardRef, useImperativeHandle } from "react";
// @ts-ignore - Reveal.js doesn't have TypeScript definitions
import Reveal from "reveal.js";
// @ts-ignore
import Markdown from "reveal.js/plugin/markdown/markdown.esm.js";
// @ts-ignore
import Highlight from "reveal.js/plugin/highlight/highlight.esm.js";
// @ts-ignore
import Notes from "reveal.js/plugin/notes/notes.esm.js";

// Props interface for the component
interface RevealPresentationProps {
  content: string; // Markdown content for the presentation
  onSlideChange?: (index: number) => void; // Callback when slide changes
}

// Handle interface for external control
export interface RevealPresentationHandle {
  goToSlide: (index: number) => void; // Method to navigate to specific slide
}

// Main presentation component with forwardRef
const RevealPresentation = forwardRef<RevealPresentationHandle, RevealPresentationProps>(
  ({ content, onSlideChange }, ref) => {
    const revealRef = useRef<HTMLDivElement>(null); // Ref for the container
    const revealInstance = useRef<Reveal.Api | null>(null); // Ref for Reveal instance

    // Expose methods to parent component
    useImperativeHandle(ref, () => ({
      goToSlide: (index: number) => {
        if (revealInstance.current) {
          revealInstance.current.slide(index);
        }
      },
     
    }));

    // Initialize Reveal.js on mount
    useEffect(() => {
      if (!revealRef.current) return;

      // Create new Reveal instance with configuration
      revealInstance.current = new Reveal(revealRef.current, {
        autoAnimate: true,
        plugins: [Markdown, Highlight, Notes],
        controls: true,
        controlsTutorial: true,
        controlsLayout: 'bottom-right',
        controlsBackArrows: 'faded',
        progress: true,
        fullscreen: true,
        embedded: true,
        transition: 'slide', // Slide transition style
        transitionSpeed: 'default', // Transition speed (fast/slow/default)
        backgroundTransition: 'fade', // Background transition
      });

      revealInstance.current.initialize();

      // Add slide change listener if callback provided
      if (onSlideChange) {
        revealInstance.current.on('slidechanged', (event: { indexh: number; }) => {
          onSlideChange(event.indexh);
        });
      }

      // Cleanup on unmount
      return () => {
        if (revealInstance.current?.isReady()) {
          revealInstance.current.destroy();
        }
      };
    }, []);

    // Handle content updates
    useEffect(() => {
      if (revealInstance.current) {
        // 保存当前幻灯片索引
        const currentIndex = revealInstance.current.getState().indexh;

        // 完全移除旧的slides
        const slidesContainer = revealRef.current?.querySelector('.slides');
        if (slidesContainer) {
          slidesContainer.innerHTML = `
            <section data-markdown
                     data-separator-notes="^note:"
                     data-separator-vertical="^---">
              <textarea data-template>${content}</textarea>
            </section>
          `;
        }

        // 安全销毁实例
        if (revealInstance.current.isReady()) {
          revealInstance.current.destroy();
        }
        
        // 重新初始化
        revealInstance.current = new Reveal(revealRef.current!, {
          autoAnimate: true,
          plugins: [Markdown, Highlight, Notes],
          controls: true,
          controlsTutorial: true,
          controlsLayout: 'bottom-right',
          controlsBackArrows: 'faded',
          progress: true,
          fullscreen: true,
          embedded: true
        });
      
        
        revealInstance.current.initialize().then(() => {
          // 恢复之前的幻灯片位置
          revealInstance.current?.slide(currentIndex);
          console.log(currentIndex)
        });
      }
    }, [content]);

    // Render presentation container
    return (
      <div className="reveal reveal-edit  [font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Noto Sans SC','Microsoft YaHei',sans-serif] w-full " ref={revealRef}>
        <div className="slides">
          <section
            data-markdown=""
            data-separator-notes="^note:"
            data-separator-vertical="^---"
          >
            <textarea 
              data-template
              defaultValue={content}
            >
              </textarea>
          </section>
        </div>
      </div>
    );
  }
);

// Set display name for debugging
RevealPresentation.displayName = 'RevealPresentation';

export default RevealPresentation;